package com.sgb.kjwl.view.ui.fragment.packers;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityQuotedPriceBinding;
import com.sgb.kjwl.model.entity.TeamPriceItemEntity;
import com.sgb.kjwl.model.entity.packers.PickResultEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.activity.packers.TeamOfferDetailActivity;
import com.sgb.kjwl.view.ui.adapter.price.QuotePriceListAdapter;
import com.sgb.kjwl.view.widget.GoodsTypePopWindow4;
import com.sgb.kjwl.view.widget.PickPopWindow1;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.quotedprice.QuotedPriceModel;
import com.sgb.link.entity.PickFilterEntity;
import com.swgk.core.base.model.entity.SelectPopEntity;
import com.swgk.core.customview.ScreenChildTextView;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.interfaces.PopClick;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.weiget.TwoLevelPopWindow;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : younghow
 * @date : 2021/12/3 11:29
 * description:工种报价
 */
public class WorkTypePriceFragment extends AppLazyFragment {

    public QuotedPriceModel viewModel;
    private ActivityQuotedPriceBinding binding;
    private QuotePriceListAdapter adapter;

    /**
     * 工程分类
     */
    private TwoLevelPopWindow<PickFilterEntity> popCategory;
    private PickResultEntity pickResultProject1;
    private PickResultEntity pickResultProject2;
    private PickResultEntity pickResultProject3;
    /**
     * 工种名称
     */
    private PickPopWindow1 popWorkType;
    private PickResultEntity pickResultWorkType;
    /**
     * 所在区域
     */
    private ThreeLevelAreaWindow popCity;
    private PickResultEntity pickResultProvince;
    private PickResultEntity pickResultCity;
    private PickResultEntity pickResultArea;
    private AddressEntity mAddress;
    private String mAreaCode,mAreaName;
    private boolean isLoadMore;
    private List<PickFilterEntity<List<PickFilterEntity<List<PickFilterEntity>>>>> workTypeList;
    private GoodsTypePopWindow4 carsTypePopWindow;
    private int typePosition = -1;
    private List<GoodsInfoTypeEntity3> carsTypeData;
    private SelectPopEntity selectPopEntity2;

    public static WorkTypePriceFragment newInstance() {
        WorkTypePriceFragment intent = new WorkTypePriceFragment();
        Bundle bundle = new Bundle();
        intent.setArguments(bundle);
        return (intent);
    }

    private void initFilterData(boolean isLoadMore) {
        this.isLoadMore = isLoadMore;
        viewModel.getList(pickResultProject1.getNo(), pickResultProject2.getNo(), pickResultProject3.getNo(),
                pickResultWorkType.getNo(), pickResultProvince.getNo(), pickResultCity.getNo(), pickResultArea.getNo(), isLoadMore);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.activity_quoted_price, container, false);
        return binding.getRoot();
    }

    @Override
    protected void initView() {


        binding.setLifecycleOwner(this);
        viewModel = new ViewModelProvider(this).get(QuotedPriceModel.class);

        mAreaCode = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_CODE,"");
        mAreaName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.AREA_NAME,"");

        binding.ivEmploymentAll.setOnClickListener(this);

        setTextButton();

        binding.sct.onSetCallPop(new ScreenChildTextView.ICallPop() {
            @Override
            public void openPop(int position, TextView content, LinearLayout bg, SelectPopEntity entity) {
                if (binding.sct.getSize() == 3){
                    if (position == 0) {
                        if (workTypeList.get(binding.rvPackerChangeFirstContentTitle.getSelectedTabPosition()).getChildren() != null) {
                            showCategoryPop();
                        }else {
                            MToast.showToast(getContext(),"该类目下无子集");
                        }
                    } else if (position == 1) {
                        showWorkTypePopWindow();
                    } else if (position == 2) {
                        showCityPop();
                    }
                }else if (binding.sct.getSize() == 2){
                    if (position == 0) {
                        showWorkTypePopWindow();
                    } else if (position == 1) {
                        showCityPop();
                    }
                }
            }
        });

        carsTypeData = new ArrayList<>();

        if (adapter == null) {
            adapter = new QuotePriceListAdapter(getActivity(), null);
        }

        adapter.setOnItemClick(new AdapterOnItemClick<TeamPriceItemEntity>() {
            @Override
            public void onItemClick(TeamPriceItemEntity teamPriceItemEntity, int position) {
                TeamOfferDetailActivity.start(getActivity(), teamPriceItemEntity.getNo());
            }
        });

        binding.list.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.list.addItemDecoration(new RecyclerCustomDecoration(
                0,
                0,
                0,
                getResources().getDimension(R.dimen.dp10)));
        binding.list.setAdapter(adapter);
        binding.list.setLoadingMoreEnabled(true);
        binding.list.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initFilterData(false);
            }

            @Override
            public void onLoadMore() {
                initFilterData(true);
            }
        });

        pickResultProject1 = new PickResultEntity();
        pickResultProject2 = new PickResultEntity();
        pickResultProject3 = new PickResultEntity();
        pickResultWorkType = new PickResultEntity();
        pickResultProvince = new PickResultEntity();
        pickResultCity = new PickResultEntity();
        pickResultArea = new PickResultEntity();


        binding.rvPackerChangeFirstContentTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                carsTypePopWindow.setDefItem(tab.getPosition());
                if (tab.getPosition() != 0){
                    pickResultProject1.setNo(workTypeList.get(tab.getPosition()).getNo());
                    pickResultProject1.setName(workTypeList.get(tab.getPosition()).getName());
                }else {
                    pickResultProject1.setNo("");
                    pickResultProject1.setName("全部");
                }

                pickResultProject2.clear();
                pickResultProject3.clear();
                initFilterData(false);
                if (tab.getPosition() == 0){
                    binding.sct.removeTextButton(selectPopEntity2);
                    return;
                }else {
                    binding.sct.addTextButton(selectPopEntity2,0);
                    binding.sct.contentSelect("工程专项",false,false,0);
                }

                List<PickFilterEntity<List<PickFilterEntity>>> data = new ArrayList<>(workTypeList.get(tab.getPosition()).getChildren());
                List<PickFilterEntity> oneLevelData = new ArrayList<>();
                List<List<PickFilterEntity>> twoLevelData = new ArrayList<>();
                if (data.size() > 0){
                    data.add(0,new PickFilterEntity("","全部"));
                    for (PickFilterEntity<List<PickFilterEntity>> datum : data) {
                        oneLevelData.add(datum);
                        List<PickFilterEntity> oneLevel = new ArrayList<>(datum.getChildren() == null ? new ArrayList<>() : datum.getChildren());
                        oneLevel.add(0,new PickFilterEntity("","全部"));
                        twoLevelData.add(oneLevel);
                    }
                }

                popCategory = new TwoLevelPopWindow<>(getActivity());
                popCategory.setBgView(binding.grayLayout);

                popCategory.setPopClick(new PopClick<PickFilterEntity>() {
                    @Override
                    public void reset() {
                        pickResultProject2.clear();
                        pickResultProject3.clear();
                        binding.sct.contentSelect("工程专项",false,false,0);
                        initFilterData(false);
                    }

                    @Override
                    public void sure(int provincePosition, int cityPosition, PickFilterEntity provinceEntity, PickFilterEntity cityEntity) {
                        if (provinceEntity != null){
                            pickResultProject2.setNo(provinceEntity.getNo());
                            pickResultProject2.setName(provinceEntity.getName());
                        }else {
                            pickResultProject2.setNo("");
                            pickResultProject2.setName("全部");
                        }

                        if (cityEntity != null){
                            pickResultProject3.setNo(cityEntity.getNo());
                            pickResultProject3.setName(cityEntity.getName());
                        }else {
                            pickResultProject3.setNo("");
                            pickResultProject3.setName("全部");
                        }

                        if (TextUtils.equals("全部", pickResultProject3.getName())) {
                            if (TextUtils.equals("全部", pickResultProject2.getName())){
                                binding.sct.contentSelect("工程专项",false,false,0);
                            }else {
                                binding.sct.contentSelect(pickResultProject2.getName(), true, false, 0);
                            }
                        } else {
                            binding.sct.contentSelect(pickResultProject3.getName(),true,false,0);
                        }
                        initFilterData(false);
                    }
                });

                popCategory.setOnDismissListener(() -> binding.sct.contentSelect(!TextUtils.equals("工程专项", binding.sct.getName(0)),false,0));
                popCategory.setLinkData(oneLevelData,twoLevelData);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        carsTypePopWindow = new GoodsTypePopWindow4(getActivity());
        carsTypePopWindow.setBgView(binding.grayLayout);
        carsTypePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object type, Object key2, Object key3) {
                GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) type;
                typePosition = (int) key2;
                pickResultProject1.setNo(entity.getNo());
                if (typePosition != 0){
                    binding.sct.addTextButton(selectPopEntity2,0);
                }
                binding.rvPackerChangeFirstContentTitle.postDelayed(() -> binding.rvPackerChangeFirstContentTitle.getTabAt(typePosition).select(), 100);
                initFilterData(false);
            }
        });
        carsTypePopWindow.setOnDismissListener(() -> binding.ivEmploymentAll.setImageResource(R.mipmap.btn_expand_team_employment));

        initLiveData();
    }

    private void initLiveData() {

        viewModel.loading.observe(getViewLifecycleOwner(), aBoolean -> DialogHelper.showProgressDialog(getContext(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false));

        viewModel.priceList.observe(getViewLifecycleOwner(), new Observer<List<TeamPriceItemEntity>>() {
            @Override
            public void onChanged(List<TeamPriceItemEntity> list) {
                if (isLoadMore) {
                    binding.list.loadMoreComplete();
                    if (list != null && list.size() > 0) {
                        adapter.addDatas(list);
                    }
                    binding.list.setNoMore(list.size() < 10);
                } else {
                    binding.list.refreshComplete();
                    if (list != null && list.size() > 0) {
                        binding.emptyView.setVisibility(View.GONE);
                        adapter.setDatas(list);
                        binding.list.smoothScrollToPosition(0);
                    } else {
                        adapter.clearDatas();
                        binding.emptyView.setVisibility(View.VISIBLE);
                    }
                }
            }
        });

        viewModel.h5Url.observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                WebViewX5HostActivity.start(getContext(), s);
            }
        });

        viewModel.categoryType.observe(getViewLifecycleOwner(), new Observer<List<PickFilterEntity<List<PickFilterEntity<List<PickFilterEntity>>>>>>() {
            @Override
            public void onChanged(List<PickFilterEntity<List<PickFilterEntity<List<PickFilterEntity>>>>> data) {
                workTypeList = data;
                for (PickFilterEntity<List<PickFilterEntity<List<PickFilterEntity>>>> datum : data) {
                    GoodsInfoTypeEntity3 info = new GoodsInfoTypeEntity3();
                    info.setName(datum.getName());
                    info.setNo(datum.getNo());
                    carsTypeData.add(info);
                    binding.rvPackerChangeFirstContentTitle.addTab(binding.rvPackerChangeFirstContentTitle.newTab().setText(datum.getName()));
                }
            }
        });

        viewModel.workType.observe(getViewLifecycleOwner(), new Observer<List<PickSelectEntity>>() {
            @Override
            public void onChanged(List<PickSelectEntity> data) {
                if (popWorkType == null) {
                    popWorkType = new PickPopWindow1(getContext());
                    popWorkType.setBgView(binding.grayLayout);
                    popWorkType.setOnResultClick((PickPopWindow1.OnResultClick) (key1, key2, key3) -> {
                        pickResultWorkType.setNo((String) key1);
                        pickResultWorkType.setName((String) key2);
                        pickResultWorkType.setPosition((int) key3);
                        if (TextUtils.isEmpty((String) key2) || TextUtils.equals("全部", (String) key2)) {
                            binding.sct.contentSelect("工种名称",false,false,binding.sct.getSize() == 3 ? 1 : 0);
                        } else {
                            binding.sct.contentSelect((String) key2,true,false,binding.sct.getSize() == 3 ? 1 : 0);
                        }
                        initFilterData(false);
                    });
                    popWorkType.setOnDismissListener(() -> binding.sct.contentSelect(!TextUtils.equals("工种名称", binding.sct.getName(binding.sct.getSize() == 3 ? 1 : 0)),false,binding.sct.getSize() == 3 ? 1 : 0));

                    popWorkType.setData(data);
                }
            }
        });

        viewModel.city.observe(getViewLifecycleOwner(), new Observer<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>() {
            @Override
            public void onChanged(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
                if (popCity == null) {
                    popCity = new ThreeLevelAreaWindow(getActivity()) {
                        @Override
                        protected void provinceClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.provinceClick(baseAreaEntity, position);
                            pickResultProvince.setNo(baseAreaEntity.getNo());
                            pickResultProvince.setName(baseAreaEntity.getSimpleName());
                            if ("全部".equals(baseAreaEntity.getSimpleName()) || pickResultProvince.getName().equals(baseAreaEntity.getSimpleName())) {
                                pickResultCity.setNo("");
                                pickResultCity.setName("");
                                pickResultArea.setNo("");
                                pickResultArea.setName("");
                            }
                        }

                        @Override
                        protected void cityClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.cityClick(baseAreaEntity, position);
                            pickResultCity.setNo(baseAreaEntity.getNo());
                            pickResultCity.setName(baseAreaEntity.getSimpleName());
                            if ("全部".equals(baseAreaEntity.getSimpleName()) || pickResultCity.getName().equals(baseAreaEntity.getSimpleName())) {
                                pickResultArea.setNo("");
                                pickResultArea.setName("");
                            }
                        }

                        @Override
                        protected void areaClick(BaseAreaEntity baseAreaEntity, int position) {
                            super.areaClick(baseAreaEntity, position);
                            pickResultArea.setNo(baseAreaEntity.getNo());
                            pickResultArea.setName(baseAreaEntity.getSimpleName());
                        }

                        @Override
                        protected void reset() {
                            super.reset();
                            pickResultProvince.clear();
                            pickResultCity.clear();
                            pickResultArea.clear();
                            binding.sct.contentSelect("全部",true,false,binding.sct.getSize() == 3 ? 2 : 1);
                            popCity.dismiss();
                            initFilterData(false);
                        }
                    };
                    popCity.setBgView(binding.grayLayout);
                    popCity.setShowSimpleName(true);
                    popCity.setProvinceSingle();
                    popCity.setCitySingle();
                    popCity.setAreaSingle();
                    pickResultProvince.setName(mAreaName);
                    popCity.setOnResultClick((key1, key2, key3) -> {
                        initFilterData(false);
                        if (!"全部".equals(pickResultArea.getName()) && !"".equals(pickResultArea.getName())) {
                            binding.sct.contentSelect(pickResultArea.getName(),true,false,binding.sct.getSize() == 3 ? 2 : 1);
                            return;
                        } else {
                            binding.sct.contentSelect(pickResultCity.getName(),true,false,binding.sct.getSize() == 3 ? 2 : 1);
                        }

                        if (!"全部".equals(pickResultCity.getName()) && !"".equals(pickResultCity.getName())) {
                            binding.sct.contentSelect(pickResultCity.getName(),true,false,binding.sct.getSize() == 3 ? 2 : 1);
                            return;
                        } else {
                            binding.sct.contentSelect(pickResultProvince.getName(),true,false,binding.sct.getSize() == 3 ? 2 : 1);
                        }

                        if (!"全部".equals(pickResultProvince.getName()) && !"".equals(pickResultProvince.getName())) {
                            binding.sct.contentSelect(pickResultProvince.getName(),true,false,binding.sct.getSize() == 3 ? 2 : 1);
                        } else {
                            binding.sct.contentSelect("全部",true,false,binding.sct.getSize() == 3 ? 2 : 1);
                        }
                    });
                    popCity.setOnDismissListener(() -> binding.sct.contentSelect(!TextUtils.equals("地区", binding.sct.getName(binding.sct.getSize() == 3 ? 2 : 1)),false,binding.sct.getSize() == 3 ? 2 : 1));

                    popCity.setDataForAll(data, true, mAreaCode);
                }
            }
        });
    }

    @Override
    protected void onLazyLoad() {
        pickResultProvince.setNo(mAreaCode);
        binding.sct.contentSelect(mAreaName,true,false,2);
        viewModel.getCategoryType();
        viewModel.getCityList();
        initFilterData(false);
        viewModel.getWorkType();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_employment_all){
            if (carsTypeData != null && carsTypeData.size() > 0){
                carsTypePopWindow.setData(carsTypeData,typePosition);
                carsTypePopWindow.showPopwindow(binding.ivEmploymentAll, 0, 0);
            }
            binding.ivEmploymentAll.setImageResource(R.mipmap.btn_expand_up_gray);
        }
    }

    public void showCategoryPop() {
        binding.sct.contentSelect(false,true,0);
        popCategory.showPopwindow0(binding.sct);
    }

    public void showWorkTypePopWindow() {
        binding.sct.contentSelect(false,true,binding.sct.getSize() == 3 ? 1 : 0);
        popWorkType.showPopwindow0(binding.sct);
    }

    public void showCityPop() {
        binding.sct.contentSelect(false,true,binding.sct.getSize() == 3 ? 2 : 1);
        popCity.showPopwindow(binding.sct, 0, 0);
    }

    public void getUrl(String url) {
        WebViewX5HostActivity.start(getContext(), url);
    }

    private void setTextButton(){
        selectPopEntity2 = new SelectPopEntity("工程专项", "0", false, true);
        SelectPopEntity selectPopEntity3 = new SelectPopEntity("工种名称", "1", false, true);
        SelectPopEntity selectPopEntity1 = new SelectPopEntity("地区", "2", false, true);
        binding.sct.addTextButton(selectPopEntity2);
        binding.sct.addTextButton(selectPopEntity3);
        binding.sct.addTextButton(selectPopEntity1);
    }
}
